package com.canyou.oss;

import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.UploadObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * minio oss文件上传
 *
 * @author fy
 * @date 2021/3/15 20:46
 */
@Service
@Slf4j
public class MinioOssService {

    @Autowired
    private MinioOssProperties config;

    public ObjectWriteResponse upload(File file, String fileName) {
        // Create a minioClient with the MinIO server playground, its access key and secret key.
        MinioClient minioClient =
                MinioClient.builder()
                        .endpoint(config.getEndpoint())
                        .credentials(config.getAccessKey(), config.getSecretKey())
                        .build();

        // Upload '/home/user/Photos/asiaphotos.zip' as object name 'asiaphotos-2015.zip' to bucket
        try {
            return minioClient.uploadObject(
                    UploadObjectArgs.builder()
                            .bucket(config.getBucket())
                            .object(fileName)
                            .filename(file.getAbsolutePath())
                            .build());
        } catch (Exception ex) {
            throw new RuntimeException("上传文件到minio oss失败", ex);
        }
    }

}
